package com.wit.witmg.config;

import com.wit.witmg.entity.DeviceSession;
import com.wit.witmg.entity.Tefdata;
import com.wit.witmg.service.ITefdataService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

@Component
@RequiredArgsConstructor
public class AdvancedTcpServer implements CommandLineRunner, DisposableBean {
    //方波数据TCP
    final ITefdataService tefdataService;

    // 配置参数
    private static final int PORT = 2404;
    private static final int MAX_THREADS = 100;
    private static final int HEARTBEAT_INTERVAL = 30; // 心跳间隔(秒)
    private static final int RECONNECT_WAIT_TIME = 5000; // 客户端重连等待时间(毫秒)

    // 连接管理
    private final ConcurrentMap<String, DeviceSession> activeSessions = new ConcurrentHashMap<>();
    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    private ScheduledExecutorService scheduler;
    private volatile boolean isRunning = true;

    @Override
    public void run(String... args) throws Exception {
        startTcpServer();
    }

    @Override
    public void destroy() throws Exception {
        // Spring容器关闭时优雅停止服务
        stopTcpServer();
    }

    private void startTcpServer() {
        threadPool = Executors.newFixedThreadPool(MAX_THREADS);
        scheduler = Executors.newScheduledThreadPool(1);

        try {
            serverSocket = new ServerSocket(PORT);
            System.out.printf("TCP服务器已启动，监听端口: %d\n", PORT);

            // 独立线程处理客户端连接
            new Thread(() -> {
                while (isRunning) {
                    try {
                        Socket clientSocket = serverSocket.accept();
                        threadPool.execute(() -> handleClient(clientSocket));
                    } catch (IOException e) {
                        if (isRunning) {
                            System.err.println("接受客户端连接异常: " + e.getMessage());
                        }
                    }
                }
            }).start();

//            startHeartbeatCheck();
        } catch (IOException e) {
            System.err.println("TCP服务器启动失败: " + e.getMessage());
            throw new RuntimeException("TCP服务器启动失败", e);
        }
    }

    private void stopTcpServer() {
        isRunning = false;

        // 关闭所有客户端连接
        activeSessions.forEach((id, session) -> {
            try {
                session.getSocket().close();
            } catch (IOException e) {
                System.err.println("关闭客户端连接异常: " + e.getMessage());
            }
        });
        activeSessions.clear();

        // 关闭线程池
        if (threadPool != null) {
            threadPool.shutdownNow();
        }
        if (scheduler != null) {
            scheduler.shutdownNow();
        }

        // 关闭服务器Socket
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                System.err.println("关闭服务器Socket异常: " + e.getMessage());
            }
        }

        System.out.println("TCP服务器已停止");
    }

    private void handleClient(Socket socket) {
        String clientIp = socket.getInetAddress().getHostAddress();
        System.out.printf("新连接来自: %s\n", clientIp);

        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

//            DeviceSession session = new DeviceSession(clientIp,socket,out);
//            activeSessions.put(clientIp, session);

            // 持续通信
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                //如果是108B00008B16，则直接回复1049FFFF4716\r\n
                if (inputLine.equals("108B00008B16")) {
                    out.println("1049FFFF4716\r\n");
                    continue; // 跳过后续处理
                }
                Tefdata tefdata = parseString(inputLine);
                if(tefdata != null){
                    tefdataService.save(tefdata);
                }
                out.println("1000FFFFFE\r\n");
            }
        } catch (IOException e) {
            System.err.println("客户端处理异常: " + e.getMessage());
        }
    }


    public Tefdata parseString(String input) {
        if (input == null || input.isEmpty()) {
            return null;
        }

        Tefdata tefdata = new Tefdata();

        String abStr = input.substring(0, 2);
        try {
            int abValue = Integer.parseInt(abStr);
            tefdata.setAb(abValue);
        } catch (NumberFormatException e) {
            // 处理格式错误的情况
            tefdata.setAb(null);
        }

        // 提取时间戳（剩余部分）
        String timestampStr = input.substring(2,10);
        try {
            long timestamp = Long.parseLong(timestampStr, 16); // 假设是16进制
            tefdata.setDt(timestamp);
        } catch (NumberFormatException e) {
            // 处理格式错误的情况
            tefdata.setDt(null);
        }

        // 处理最后一个字符（合格状态）
        String lastPart = input.substring(input.length() - 1);
        if (!lastPart.isEmpty()) {
            switch (lastPart) {
                case "1":
                    tefdata.setHeGe(0); // 0 -> 合格
                    break;
                case "2":
                    tefdata.setHeGe(1); // 1 -> 未知
                    break;
                case "0":
                    tefdata.setHeGe(2); // 2 -> 不合格
                    break;
                default:
                    tefdata.setHeGe(null); // 其他值设为null
            }
        }

        // 保存原始数据
        tefdata.setData(input);
        return tefdata;
    }



    // 增强版心跳检测
//    private void startHeartbeatCheck() {
//        scheduler.scheduleAtFixedRate(() -> {
//            long now = System.currentTimeMillis();
//            activeSessions.entrySet().removeIf(entry -> {
//                DeviceSession session = entry.getValue();
//                if (now - session.getLastActiveTime() > HEARTBEAT_INTERVAL * 1000) {
//                    try {
//                        // 发送心跳检测
////                        session.getWriter().println("HEARTBEAT_CHECK");
//                        // 检查连接是否仍然活跃
//                        if (session.getSocket().isClosed() || !session.getSocket().isConnected()) {
//                            tcpCommandService.removeConnection(entry.getKey());
//                            return true; // 移除无效连接
//                        }
//                    } catch (Exception e) {
//                        System.out.println("心跳检测失败，设备断开: " + entry.getKey());
//                        tcpCommandService.removeConnection(entry.getKey());
//                        return true; // 移除无效连接
//                    }
//                }
//                return false;
//            });
//        }, HEARTBEAT_INTERVAL, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
//    }

    // 管理控制台
//    private void startAdminConsole() {
//        new Thread(() -> {
//            Scanner scanner = new Scanner(System.in);
//            while (true) {
//                System.out.print("Server> ");
//                String cmd = scanner.nextLine().trim();
//
//                if (cmd.equals("list")) {
//                    System.out.println("Connected devices (" +
//                            activeSessions.size() + "):");
//                    activeSessions.forEach((id, session) ->
//                            System.out.printf("- %s (IP: %s, Active: %ds ago)\n",
//                                    id,
//                                    session.socket.getInetAddress(),
//                                    (System.currentTimeMillis() - session.lastActiveTime)/1000
//                            )
//                    );
//                } else if (cmd.startsWith("kick ")) {
//                    String deviceId = cmd.substring(5);
//                    DeviceSession session = activeSessions.get(deviceId);
//                    if (session != null) {
//                        try {
//                            session.socket.close();
//                            System.out.println("Device kicked: " + deviceId);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        }).start();
//    }

    // 根据Socket查找设备ID
//    private String findDeviceIdBySocket(Socket socket) {
//        for (Map.Entry<String, DeviceSession> entry : activeSessions.entrySet()) {
//            if (entry.getValue().socket == socket) {
//                return entry.getKey();
//            }
//        }
//        return null;
//    }


}